/**
 * 认证状态管理
 * 管理用户登录、登出、权限验证等功能
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { UserInfo, LoginForm } from '@/types'
import { storage, StorageKey } from '@/utils/storage'
import { login as loginApi } from '@/api'
import { message } from 'ant-design-vue'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref<string | null>(storage.get<string>(StorageKey.TOKEN))
  const userInfo = ref<UserInfo | null>(storage.get<UserInfo>(StorageKey.USER_INFO))

  // 计算属性
  const isAuthenticated = computed(() => !!token.value)
  const isAdmin = computed(() => userInfo.value?.role === 'admin')

  /**
   * 登录
   */
  async function login(form: LoginForm): Promise<boolean> {
    try {
      const res = await loginApi(form)

      if (res.success && res.data) {
        // 保存 token 和用户信息
        token.value = res.data.token
        userInfo.value = res.data.user

        // 持久化存储
        storage.set(StorageKey.TOKEN, res.data.token)
        storage.set(StorageKey.USER_INFO, res.data.user)

        // 记住我功能
        if (form.remember) {
          storage.set(StorageKey.REMEMBER_ME, form.username)
        } else {
          storage.remove(StorageKey.REMEMBER_ME)
        }

        message.success(res.message || '登录成功')
        return true
      } else {
        message.error(res.message || '登录失败')
        return false
      }
    } catch (error: any) {
      message.error(error.message || '登录失败')
      return false
    }
  }

  /**
   * 登出
   */
  function logout(): void {
    token.value = null
    userInfo.value = null

    // 清空存储
    storage.remove(StorageKey.TOKEN)
    storage.remove(StorageKey.USER_INFO)

    message.success('已退出登录')
  }

  /**
   * 检查认证状态
   */
  function checkAuth(): boolean {
    return isAuthenticated.value
  }

  /**
   * 更新用户信息
   */
  function updateUserInfo(info: Partial<UserInfo>): void {
    if (userInfo.value) {
      userInfo.value = { ...userInfo.value, ...info }
      storage.set(StorageKey.USER_INFO, userInfo.value)
    }
  }

  /**
   * 获取记住的用户名
   */
  function getRememberedUsername(): string | null {
    return storage.get<string>(StorageKey.REMEMBER_ME)
  }

  return {
    // 状态
    token,
    userInfo,
    isAuthenticated,
    isAdmin,

    // 方法
    login,
    logout,
    checkAuth,
    updateUserInfo,
    getRememberedUsername,
  }
})
